
// #ifdef H5
import WechatJSSDK from "@/libs/jweixin-module/index.js";
import {getWechatConfig,wechatAuth} from "@/api/public";
import {wxLogin} from "@/api/login.js";
import {userLogin} from "@/api/useryk.js";
import {
	WX_AUTH,
	STATE_KEY,
	LOGINTYPE,
	BACK_URL
} from '@/config/store.js';
import {parseQuery} from '@/utils';
import store from '@/store';
import Cache from '@/utils/cache';
import {wxappid,Http_url} from "@/config/config"
class AuthWechat {

	constructor() {
		//微信实例化对象
		this.instance = WechatJSSDK;
		//是否实例化
		this.status = false;

		this.initConfig = {};

	}
	
	isAndroid(){
		let u = navigator.userAgent;
		return u.indexOf('Android') > -1 || u.indexOf('Adr') > -1;
	}
	
	signLink() {
		if (typeof window.entryUrl === 'undefined' || window.entryUrl === '') {
			  	window.entryUrl = location.href.split('#')[0]
			}
		return  /(Android)/i.test(navigator.userAgent) ? location.href.split('#')[0] : window.entryUrl;
	}

	/**
	 * 初始化wechat(分享配置)
	 */
	wechat() {
		return new Promise((resolve, reject) => {
			// if (this.status && !this.isAndroid()) return resolve(this.instance);
			getWechatConfig()
			.then(res => {
				// console.log('wechat res',res)
				let config={
					appId: res.data.appId,
					debug:false,
					jsApiList:[
                        'updateAppMessageShareData', 'updateTimelineShareData',
                        	'editAddress', 'chooseImage',
                        	'onMenuShareAppMessage', 'onMenuShareTimeline',
                        	'chooseImage','scanQRCode',
                        	'previewImage', 'uploadImage',
                        	'downloadImage', 'chooseWXPay',
                        	'getLocation', 'openLocation'
                    ],
					jsApiTicket:"",
					nonceStr: res.data.nonceStr,
					signature: res.data.signature,
					timestamp: res.data.timestamp,
					url:Http_url
				}
                
                // console.log(config)
                
				this.instance.config(config);
				this.initConfig = config;
				this.status = true;
				this.instance.ready(() => {
					// console.log('instance',this.instance)
					resolve(this.instance);
				})
			}).catch(err => {
				console.log('微信分享配置失败',err);
				this.status = false;
				reject(err);
			});
		});
	}
    
    // 判断当前客户端版本是否支持指定JS接口
     checkWxJsApi(jsApiList, call = () => {}){
        WechatJSSDK.checkJsApi({ 
            jsApiList, // 需要检测的JS接口列表，所有JS接口列表见附录2,
            success: function(res) {
              const {checkResult} = res
              let shareApi = Object.keys(checkResult).filter(api => checkResult[api])
              console.log('shareApi', shareApi)
              call(shareApi)
            }
        });
    }
    /**
     * 微信分享
     * @param {Object} params
     */
    share(params){
        return new Promise((resolve, reject) => {
        	this.wechat().then(wx => {
                
                const shareData = {
                	title: params?.title || '',
                	desc: params?.desc || '',
                	link: params?.link || window.location.href,
                	imgUrl: params?.imgUrl ,
                	success: (res) => {
                		//用户点击分享后的回调，这里可以进行统计，例如分享送金币之类的
                		params?.success()
                	}
                }
                       
                // // 自定义“分享给朋友”及“分享到QQ”按钮的分享内容
                // jweixin.updateAppMessageShareData(shareData)
                // // 分享到朋友圈接口  
                // jweixin.updateTimelineShareData(shareData)
                // jweixin.onMenuShareAppMessage(shareData)
                // jweixin.onMenuShareTimeline(shareData)
                
                const jsApiList = [
                  // 即将废弃api, [https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/JS-SDK.html#10]
                  'onMenuShareTimeline', 'onMenuShareAppMessage', 'onMenuShareQZone',
                  // 客户端6.7.2及JSSDK 1.4.0以上版本支持api
                  'updateAppMessageShareData', 'updateTimelineShareData'
                ]
                
                this.checkWxJsApi(jsApiList, (shareApi) => {
                    shareApi.forEach(api => {
                      try{
                        console.log(api)
                        wx[api](shareData)
                      }catch(e){
                        console.log(e)
                        console.error(`不支持wx api：${api}`)
                      }
                    })
                    resolve(wx)
                })
                
        	}).catch(err => {
        		reject(err);
        	})
        });
    }

	/**
	 * 验证是否初始化
	 */
	verifyInstance() {
		let that = this;
		return new Promise((resolve, reject) => {
			if (that.instance === null && !that.status) {
				that.wechat().then(res => {
					resolve(that.instance);
				}).catch(() => {
					return reject();
				})
			} else {
				return resolve(that.instance);
			}
		})
	}
	// 微信公众号的共享地址
	openAddress() {
		return new Promise((resolve, reject) => {
			this.wechat().then(wx => {
				this.toPromise(wx.openAddress).then(res => {
					resolve(res);
				}).catch(err => {
					reject(err);
				});
			}).catch(err => {
				reject(err);
			})
		});
	}

    // 获取经纬度；
	location(){
		return new Promise((resolve, reject) => {
			this.wechat().then(wx => {
				this.toPromise(wx.getLocation,{type: 'wgs84'}).then(res => {
					resolve(res);
				}).catch(err => {
					reject(err);
				});
			}).catch(err => {
				reject(err);
			})
		});
	} 
	
	// 使用微信内置地图查看位置接口；
	seeLocation(config){
		return new Promise((resolve, reject) => {
			this.wechat().then(wx => {
				this.toPromise(wx.openLocation, config).then(res => {
					resolve(res);
				}).catch(err => {
					reject(err);
				});
			}).catch(err => {
				reject(err);
			})
		});
	}
	
	/**
	 * 微信支付
	 * @param {Object} config
	 */
	pay(config) {
		return new Promise((resolve, reject) => {
			this.wechat().then((wx) => {
				console.log('wx',wx)
				this.toPromise(wx.chooseWXPay, config).then(res => {
					resolve(res);
				}).catch(res => {
					resolve(res);
				});
			}).catch(res => {
				reject(res);
			});
		});
	}
	
	toPromise(fn, config = {}) {
		return new Promise((resolve, reject) => {
			fn({
				...config,
				success(res) {
					resolve(res);
				},
				fail(err) {
					reject(err);
				},
				complete(err) {
					reject(err);
				},
				cancel(err) {
					reject(err);
				}
			});
		});
	}

	/**
	 * 自动去授权
	 */
	oAuth(snsapiBase,url) {
		if (uni.getStorageSync(WX_AUTH) && store.state.app.token && snsapiBase == 'snsapi_base') return;
		const {
			code
		} = parseQuery();
		if (!code || code == uni.getStorageSync('snsapiCode')){
			// console.log('oAuthurl',url)
			return this.toAuth(snsapiBase,url);
		}else{
			if(Cache.has('snsapiKey'))
				return this.auth(code).catch(error=>{
					uni.showToast({
						title:error,
						icon:'none'
					})
				})
		}
		// if (uni.getStorageSync(WX_AUTH) && store.state.app.token) return;
		// const {
		// 	code
		// } = parseQuery();
		// if (!code){
		// 	return this.toAuth(snsapiBase,url);
		// }else{
		// 	if(Cache.has('snsapiKey'))
		// 		return this.auth(code).catch(error=>{
		// 			uni.showToast({
		// 				title:error,
		// 				icon:'none'
		// 			})
		// 		})
		// }
	}

	clearAuthStatus() {

	}

	/**
	 * 群主授权登录获取token
	 * @param {Object} code
	 * @param {Object} jxid
	 */
	auth(code,jxid) {
		return new Promise((resolve, reject) => {
			let param={
				jxid:jxid,
				code:code
			}

			wxLogin(param).then(data=>{
				resolve(data)
				Cache.set(WX_AUTH, code);
				Cache.clear(STATE_KEY);
				loginType && Cache.clear(LOGINTYPE);
			}).catch(reject)
		});
	}

	/**
	 * 会员授权登录获取token
	 * @param {Object} code
	 * @param {Object} qunid
	 */
	userAuth(code,qunid) {
		return new Promise((resolve, reject) => {
			let param={
				qunid:qunid,
				code:code
			}
			userLogin(param).then(data=>{
				// console.log('')
				resolve(data)
				Cache.set(WX_AUTHS, code);
				Cache.clear(STATE_U_KEY);
				loginType && Cache.clear(LOGINTYPE);
			}).catch(reject)
		});
	}

	/**
	 * 获取跳转授权后的地址
	 * @param {Object} appId
	 */
	getAuthUrl(appId,snsapiBase,backUrl) {
		let url = `${location.origin}${backUrl}`
		if(url.indexOf('?') == -1){
					url = url+'?'
				}else{
					url = url+'&'
				}
		const redirect_uri = encodeURIComponent(
			`${url}scope=${snsapiBase}&back_url=` +
			encodeURIComponent(
				encodeURIComponent(
					uni.getStorageSync(BACK_URL) ?
					uni.getStorageSync(BACK_URL) :
					location.pathname + location.search
				)
			)
		);
		// console.log('redirect_uri',redirect_uri)
		uni.removeStorageSync(BACK_URL);
		const state = encodeURIComponent(
			("" + Math.random()).split(".")[1] + "authorizestate"
		);
		uni.setStorageSync(STATE_KEY, state);
		// console.log('state',state)
		// let Rurl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_userinfo&state=${state}#wechat_redirect`
		// return Rurl;
		if(snsapiBase==='snsapi_base'){
			return `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_base&state=${state}#wechat_redirect`;
		}else{
			return `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_userinfo&state=${state}#wechat_redirect`;
		}
    }
	
	/**
	 * 跳转自动登录
	 */
	toAuth(snsapiBase,backUrl) {
		let that = this;
		this.wechat().then(wx => {
			// console.log('toAuth',backUrl)
			location.href = this.getAuthUrl(that.initConfig.appId,snsapiBase,backUrl);
		})
	}

	/**
	 * 绑定事件
	 * @param {Object} name 事件名
	 * @param {Object} config 参数
	 */
	wechatEvevt(name, config) {
		let that = this;
		return new Promise((resolve, reject) => {
			let configDefault = {
				fail(res) {
					if (that.instance) return reject({
						is_ready: true,
						wx: that.instance
					});
					that.verifyInstance().then(wx => {
						return reject({
							is_ready: true,
							wx: wx
						});
					})
				},
				success(res) {
					return resolve(res,2222);
				}
			};
			Object.assign(configDefault, config);
			that.wechat().then(wx => {
				if (typeof name === 'object') {
					name.forEach(item => {
						wx[item] && wx[item](configDefault)
					})
				} else {
					wx[name] && wx[name](configDefault)
				}
			})
		});
	}

	isWeixin() {
		console.log('isWeixin',navigator.userAgent.toLowerCase())
		return navigator.userAgent.toLowerCase().indexOf("micromessenger") !== -1;
	}

}

export default new AuthWechat();
// #endif
